package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.SysLossImportListener;
import com.settlement.system.model.entity.SysLoss;
import com.settlement.system.model.form.LossForm;
import com.settlement.system.model.query.LossPageQuery;
import com.settlement.system.model.vo.LossResultVo;
import com.settlement.system.model.vo.SysLossImportVo;
import com.settlement.system.service.SysLossService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 损失细类表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-24
 */
@Tag(name = "损失细类表")
@RestController
@RequestMapping("/api/v1/loss")
@RequiredArgsConstructor
public class SysLossController {
    private final SysLossService sysLossService;


    @Operation(summary = "损失细类表分页列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysLoss> getLossPage(@ParameterObject LossPageQuery queryParams) {
        IPage<SysLoss> result = sysLossService.getPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "保存损失细类表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:loss:save')")
    @PreventDuplicateSubmit
    public Result saveLoss(@RequestBody @Valid LossForm lossForm) {
        boolean result = sysLossService.saveLoss(lossForm);
        return Result.judge(result);
    }

    @Operation(summary = "损失细类表表单数据", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{lossId}/form")
    public Result<SysLoss> getLossForm(@Parameter(description = "损失细类表ID") @PathVariable Long lossId) {
        SysLoss sysLoss = sysLossService.getLossFormData(lossId);
        return Result.success(sysLoss);
    }

    @Operation(summary = "删除损失细类表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:loss:delete')")
    public Result deletePlatforms(@Parameter(description = "损失细类表ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysLossService.deleteLosses(ids);
        return Result.judge(result);
    }

    @Operation(summary = "获取下一个损失原因细则编码", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/nextCode/{code}")
    public Result<LossResultVo> nextCode(@Parameter(description = "损失细类编码") @PathVariable String code) {
        LossResultVo result = sysLossService.nextCode(code);
        return Result.success(result);
    }


    @Operation(summary = "导入损失细类", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/_import")
    public Result<?> importLosses(MultipartFile file) throws IOException {
        SysLossImportListener listener = new SysLossImportListener();
        EasyExcelFactory.read(file.getInputStream(), SysLossImportVo.class, listener).sheet(0).doRead();
        sysLossService.importBatch(listener.getVos());
        return Result.success("导入成功");
    }

    @Operation(summary = "导出损失细类", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    public void exportLosses(HttpServletResponse response) throws IOException {
        String fileName = "损失细类.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysLossImportVo> sysLossImportVos = sysLossService.listExportLosses();
        EasyExcel.write(response.getOutputStream(), SysLossImportVo.class).sheet("损失细类").doWrite(sysLossImportVos);
    }

    @Operation(summary = "所有损失细类", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/list")
    public Result<List<LossResultVo>> getListByLossCode() {
        List<LossResultVo> vos = sysLossService.listAll();
        return Result.success(vos);
    }
}
